package com.toobigtofail.shapes
{
	import Box2D.Common.Math.b2Vec2;
	import Box2D.Dynamics.b2Body;
	import Box2D.Dynamics.b2Fixture;
	
	import fabulaexmachina.box2fp.Box2DEntity;
	import fabulaexmachina.box2fp.Box2DShapeBuilder;
	import fabulaexmachina.box2fp.Box2DWorld;
	
	import net.flashpunk.FP;
	
	public class Line extends Box2DEntity implements IShape
	{
		private var _savedOptions:Object;
		
		public function Line(x:Number, y:Number, verts:Array, b2Type:int=0, group:int=0, category:int=0, collmask:int=0, friction:Number=0.3, density:Number=1, restitution:Number=0.3)
		{
			for each (var v:b2Vec2 in verts) {
				v.Multiply(1/(FP.world as Box2DWorld).scale);
			}
			
			_savedOptions = {group: group, 
				             category: category, 
							 collmask: collmask, 
							 friction: friction, 
							 density: density, 
							 restitution: restitution,
						     b2Type: b2Type,
							 verts: verts};
			
			super(x, y, 0, 0, b2Type, group, category, collmask, friction, density, restitution);
		}
		
		override public function buildShapes(friction:Number, 
									density:Number, restitution:Number,
									group:int, category:int, collmask:int):void {
			buildShape(body);
		}
		
		public function buildShape(body:b2Body):void {
			var verts:Array = _savedOptions.verts;
			for (var i:int = 0; i < verts.length-1; i++) {
				var lineSegment:Array = new Array;
				lineSegment.push(verts[i], verts[i+1]);
				Box2DShapeBuilder.buildPolygon(body, lineSegment, _savedOptions.friction, _savedOptions.density, _savedOptions.restitution, _savedOptions.group, _savedOptions.category, _savedOptions.collmask);
			}			
		}
		
		public function get b2Type():int { return _savedOptions.b2Type; }
		
		public static function absoluteToRelative(origX:Number, origY:Number, verts:Array):Array {
			var newVerts:Array = new Array;
			var origin:b2Vec2 = new b2Vec2(origX,origY);
			for each (var v:b2Vec2 in verts) {
				var newV:b2Vec2 = v.Copy();
				newV.Subtract(origin);
				newVerts.push(newV);
			}
			return newVerts;
		}
		
		public function serialize():XML {
			var shape:XML = <shape type="Line"/>;
			shape.@x = x;
			shape.@y = y;
			shape.@b2Type = b2Type;
			shape.@width = width;
			shape.@height = height;
			
			for each (var v:b2Vec2 in _savedOptions.verts) {
				var p:XML = <point/>;
				p.@x = v.x * (FP.world as Box2DWorld).scale;
				p.@y = v.y * (FP.world as Box2DWorld).scale;
				shape.appendChild(p);
			}
			
			return shape;
		}
	}
}